//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj添加成员 编辑成员资料

#import "AddMemberVC.h"
#import "SetNameController.h"
#import "UpgradeGoutSchemeView.h"
#import "BindPhoneNumberVC.h"
#import "PhysicalInfoController.h"
#import "MemberInfoVC.h"
#import "MJPhotoHelper.h"
#import "MJPickerViewAlertView.h"

@interface AddMemberVC ()
@property (weak, nonatomic) IBOutlet MJUICellImageTextView *nicknameItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageBTextView *birthdateItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageTextView *genderItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageBTextView *phoneItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageTextView *heightItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageTextView *weightItemView;
@property (nonatomic, assign) NSInteger genderType;
@property (weak, nonatomic) IBOutlet MJUIBaseButton *confirmButton;
@property (nonatomic, strong) NSDictionary *countryAreaCode;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (nonatomic, strong) UIImage *uploadImage;

@property (nonatomic, strong) NSString *height;
@property (nonatomic, strong) NSString *weight;
@end

@implementation AddMemberVC


- (void)viewDidLoad {
    self.backgroundColorType = BackgroundColorTypeGray;
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)mj_setUI{
    [super mj_setUI];
    
    self.mj_titleLocalizable = @"Add Member";
    self.genderItemView.rightImageView.image = MJUIImageMake(@"icon_shangxiajiantou");
    self.genderType = -1;
    
    MJWeakSelf
    //手动设置内容得加 RACObserve(self.nicknameItemView.subTitleTextField, text)
    [[RACSignal merge:@[self.nicknameItemView.subTitleTextField.rac_textSignal, RACObserve(self.nicknameItemView.subTitleTextField, text),self.birthdateItemView.subTitleTextField.rac_textSignal, RACObserve(self.birthdateItemView.subTitleTextField, text),self.genderItemView.subTitleTextField.rac_textSignal, RACObserve(self.genderItemView.subTitleTextField, text)]] subscribeNext:^(NSString* text){
        [weakSelf updateUI];
    }];
    
    //    [self handleHeightWeightButtonClick:nil];
    
    if(self.patientModel){
        self.mj_titleLocalizable = @"Edit Member Info";

        NSString *birthday = self.patientModel.birthday;
        self.nicknameItemView.subTitleTextField.text = self.patientModel.patientName;
        self.birthdateItemView.subTitleTextField.text = [birthday mj_stringConvertToFormatStringByFormat:MJUIDateFormat19 OriginalFormat:MJUIDateFormat2];
        self.genderItemView.subTitleTextField.text = MJUILocalizedString(self.patientModel.gender);
        self.phoneItemView.subTitleTextField.text = self.patientModel.phoneNumber;
        
        self.height = self.patientModel.height > 0 ? @(self.patientModel.height).description : nil;
        self.weight = self.patientModel.weight > 0 ? @(self.patientModel.weight).description : nil;
        
        self.heightItemView.subTitleTextField.text = self.height.length ? [self.height stringByAppendingString:@" cm"] : nil;
        self.weightItemView.subTitleTextField.text = self.weight.length ? [self.weight stringByAppendingString:@" kg"] : nil;
        
        [self.iconImageView mj_setHeadImageWithURLString:self.patientModel.headPic gender:self.patientModel.gender];
        if(self.patientModel.gender){
            self.genderType = self.patientModel.isMale ? 0:1;
        }
    }
    
    self.phoneItemView.subTitleTextField.adjustsFontSizeToFitWidth = true;
}

#pragma mark - 方法
- (void)updateUI {
    BOOL enable = false;
    if(self.nicknameItemView.subTitleTextField.text.length > 0 && self.birthdateItemView.subTitleTextField.text.length > 0 && self.genderItemView.subTitleTextField.text.length > 0){
        enable = true;
    }
    if(enable){
        self.confirmButton.alpha = 1;
    }else{
        self.confirmButton.alpha = 0.5;
    }
}

- (IBAction)handlePictureButtonClick:(UIButton *)sender {
    MJWeakSelf
    [MJPhotoHelper.shared getSelectPhotoWithBlock:^(UIImage *image) {
        weakSelf.iconImageView.image = image;
        UIImage *resizeImage = [image mj_resizeImageTargetSize:CGSizeMake(200, 200)];
        UIImage *newImage = [resizeImage mj_compressToSize:120];
        NSLog(@"Size1111=======================%@",[newImage mj_calulateImageFileSize]);
        weakSelf.uploadImage = newImage;
        //        [weakSelf uploadPhotoWithImage:newImage];
    }];
}

- (void)uploadPhotoWithImage:(UIImage *)image patientId:(NSString *)patientId completion:(void (^)(NSString *headPic))completion{
    MJWeakSelf
    [MJHttpNetWorking uploadImageWithParams:@{@"patientId":patientId} requestUri:oss_patient_headPic image:image showLoading:true success:^(MJBaseModel *model) {
        NSLog(@"uploadPhotoWithImage=======================%@",model.data);
        if(model.data){
            NSString *headPic = (NSString *)model.data;
            completion(headPic);
         
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (IBAction)handleSaveButtonClick:(UIButton *)sender {
    MJWeakSelf
    if(self.nicknameItemView.subTitleTextField.text.length == 0){
        [RoyHud showToast:MJUILocalizedString(@"Member name not entered")];
        return;
    }
    if(self.birthdateItemView.subTitleTextField.text.length == 0){
        [RoyHud showToast:MJUILocalizedString(@"Birth date not entered")];
        return;
    }
    if(self.genderItemView.subTitleTextField.text.length == 0){
        [RoyHud showToast:MJUILocalizedString(@"Gender not entered")];
        return;
    }
    
    if(self.phoneItemView.subTitleTextField.text.length == 0){
        MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
        configure.confirmButtonColor = UIColor.mj_appColor;
        configure.confirmTitle = MJUILocalizedString(@"OK_hd");
        configure.cancelTitle = MJUILocalizedString(@"Not Now");
        configure.messageAlignmentCenter = true;
        NSString *messageString = MJUILocalizedString(@"Phone number is empty. Would you like to bind now?");
        [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Bind Phone Number") message:messageString configure:configure confirmBlock:^{
            [weakSelf handlePhoneButtonClick:nil];
        } cancelBlock:^{
            [weakSelf requestData];
        }];
        return;
    }
    
    [self requestData];
    
}
//- (void)uploadNewImage{
//    if(self.uploadImage){
//        [self uploadPhotoWithImage:self.uploadImage];
//    }else{
//        [self requestData];
//    }
//}
- (IBAction)handleNicknameButtonClick:(UIButton *)sender {
    
    MJWeakSelf
    SetNameController *vc = [[SetNameController alloc]init];
    vc.titleItemType = TitleItemTypeMemberName;
    vc.text = self.nicknameItemView.subTitleTextField.text;
    vc.handleTitleBlock = ^(NSString *title) {
        weakSelf.nicknameItemView.subTitleTextField.text = title;
    };
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleBirthdateButtonClick:(UIButton *)sender {
    
    MJWeakSelf
    MJPickerViewAlertView *selectDateAlertView = [[MJPickerViewAlertView alloc] init];
    selectDateAlertView.date = self.birthdateItemView.subTitleTextField.text;
    selectDateAlertView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    selectDateAlertView.confirmBlock = ^(NSString *date) {
        weakSelf.birthdateItemView.subTitleTextField.text = date;
    };
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self.navigationController presentViewController:selectDateAlertView animated:NO completion:nil];
    
//    MJUIAlertTimeConfigure *configure = [[MJUIAlertTimeConfigure alloc]init];
//    configure.datePickerMode = UIDatePickerModeDate;
//    configure.maximumDate = [NSDate new];
//    [MJUICustomTimeView showTimeAlertViewWithTitle:@"Select  Birth Date" timeString:self.birthdateItemView.subTitleTextField.text configure:configure selectIndexBlock:^(NSDate *date) {
//        
//        NSString *dateString = [date mj_dateConvertToStringByFormat:MJUIDateFormat2];
//        weakSelf.birthdateItemView.subTitleTextField.text = dateString;
//        //        [weakSelf enabledDoneButton];
//        
//    }];
}

- (IBAction)handleGenderButtonClick:(UIButton *)sender {
    MJWeakSelf
    CGRect targetRect = [self.genderItemView.subTitleTextField convertRect:self.genderItemView.subTitleTextField.bounds toView:self.view];
    UpgradeGoutSchemeView *addVC = [[UpgradeGoutSchemeView alloc] init];
    addVC.targetRect = targetRect;
    addVC.type = self.genderType;
    addVC.confirmBlock = ^(NSInteger type) {
        weakSelf.genderType = type;
        if(type == 0){
            weakSelf.genderItemView.subTitleTextField.text = MJUILocalizedString(@"Male");
        }else{
            weakSelf.genderItemView.subTitleTextField.text = MJUILocalizedString(@"Female");
        }
        if(!weakSelf.uploadImage){
            [weakSelf.iconImageView mj_setHeadImageWithURLString:weakSelf.patientModel.headPic gender:type == 0 ? @"Male":@"Female"];
        }
    };
    addVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self.navigationController presentViewController:addVC animated:NO completion:nil];
}

- (IBAction)handlePhoneButtonClick:(UIButton *)sender {
    
    MJWeakSelf
    BindPhoneNumberVC *vc = [[BindPhoneNumberVC alloc]init];
    vc.handleCountryAreaCodeBlock = ^(NSDictionary *countryAreaCode,NSString *phone) {
        weakSelf.countryAreaCode = countryAreaCode;
        weakSelf.phoneItemView.subTitleTextField.text = phone;
    };
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleHeightWeightButtonClick:(UIButton *)sender {
    
    MJWeakSelf
    PhysicalInfoController *vc = [[PhysicalInfoController alloc]init];
    vc.height = self.height;
    vc.weight = self.weight;
    vc.handleTitleBlock = ^(NSString *height,NSString *weight) {
        weakSelf.height = height;
        weakSelf.weight = weight;
        weakSelf.heightItemView.subTitleTextField.text = height.length ? [height stringByAppendingString:@" cm"] : height;
        weakSelf.weightItemView.subTitleTextField.text = weight.length ? [weight stringByAppendingString:@" kg"] : weight;;
    };
    [self.navigationController pushViewController:vc animated:true];
}
- (void)handleBackButtonClick {
    
    if(self.patientModel){
        //判断是否编辑过

        NSInteger genderType = self.patientModel.isMale ? 0:1;
        NSString *birthday = [self.patientModel.birthday mj_stringConvertToFormatStringByFormat:MJUIDateFormat19 OriginalFormat:MJUIDateFormat2];
        CGFloat weight = self.weightItemView.subTitleTextField.text.length ? [self.weightItemView.subTitleTextField.text floatValue] : 0;
        CGFloat height = self.heightItemView.subTitleTextField.text.length ? [self.heightItemView.subTitleTextField.text floatValue] : 0;
        NSString *phoneNumber = self.phoneItemView.subTitleTextField.text.length ? self.phoneItemView.subTitleTextField.text : @"";
        if(![self.nicknameItemView.subTitleTextField.text isEqualToString:self.patientModel.patientName]
           || self.genderType != genderType
           || ![self.birthdateItemView.subTitleTextField.text isEqualToString:birthday]
           || ![phoneNumber isEqualToString:self.patientModel.phoneNumber.length ? self.patientModel.phoneNumber : @""]
           || weight != self.patientModel.weight
           || height != self.patientModel.height){
            MJWeakSelf
            MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
            configure.confirmButtonColor = UIColor.mj_appColor;
            configure.confirmTitle = MJUILocalizedString(@"Yes");
            configure.cancelTitle = MJUILocalizedString(@"Cancel_qx");
            configure.messageAlignmentCenter = true;
            NSString *messageString = MJUILocalizedString(@"You have unsaved changes. Are you sure you want to exit?");
            [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Unsaved Changes") message:messageString configure:configure confirmBlock:^{
                [weakSelf mj_popViewController];
            } cancelBlock:^{
                
            }];
        }else{
            [self mj_popViewController];
        }
        
    }else{
        
        if(self.nicknameItemView.subTitleTextField.text.length > 0 || self.birthdateItemView.subTitleTextField.text.length > 0 || self.genderItemView.subTitleTextField.text.length > 0 ||
           self.phoneItemView.subTitleTextField.text.length > 0 ||
           self.heightItemView.subTitleTextField.text.length > 0 ||
           self.weightItemView.subTitleTextField.text.length > 0){
            MJWeakSelf
            MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
            configure.confirmButtonColor = UIColor.mj_appColor;
            configure.confirmTitle = MJUILocalizedString(@"Yes");
            configure.cancelTitle = MJUILocalizedString(@"Cancel_qx");
            configure.messageAlignmentCenter = true;
            NSString *messageString = MJUILocalizedString(@"You have unsaved changes. Are you sure you want to exit?");
            [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Information Not Saved") message:messageString configure:configure confirmBlock:^{
                [weakSelf mj_popViewController];
            } cancelBlock:^{
                
            }];
        }else{
            [self mj_popViewController];
        }
    }
}

- (void)requestData{
    
    MJWeakSelf
    NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
        @"patientName":self.nicknameItemView.subTitleTextField.text,
        @"gender":self.genderType == 0 ? @"Male":@"Female",
        @"birthday":[self.birthdateItemView.subTitleTextField.text stringByAppendingString:@"-01"],
    }];
    if(self.phoneItemView.subTitleTextField.text.length){
        [parms setObject:self.phoneItemView.subTitleTextField.text forKey:@"phoneNumber"];
    }
    if(self.height.length){
        [parms setObject:self.height forKey:@"height"];
    }
    if(self.weight.length){
        [parms setObject:self.weight forKey:@"weight"];
    }
    if(self.countryAreaCode){
        [parms setObject:self.countryAreaCode[@"区号"] forKey:@"countryCode"];
    }
    if(self.patientModel){
        [parms setObject:self.patientModel.patientId forKey:@"patientId"];
    }
    [MJHttpNetWorking requestWithParams:parms requestUri:patient_select requestType:self.patientModel ? RequestTypePut : RequestTypePost showLoading:true success:^(MJBaseModel *model) {
        
        if(model.code == 200){
            
            if(weakSelf.patientModel){
                PatientModel *patientModel = [PatientModel yy_modelWithDictionary:model.data];
                if(weakSelf.uploadImage){
                    [weakSelf uploadPhotoWithImage:weakSelf.uploadImage patientId:patientModel.patientId completion:^(NSString *headPic) {
                        patientModel.headPic = headPic;
                        [weakSelf popViewController:patientModel];
                    }];
                }else{
                    [weakSelf popViewController:patientModel];
                }
            }else{
                PatientModel *patientModel = [PatientModel yy_modelWithDictionary:model.data];
                if(weakSelf.uploadImage){
                    [weakSelf uploadPhotoWithImage:weakSelf.uploadImage patientId:patientModel.patientId completion:^(NSString *headPic) {
                        patientModel.headPic = headPic;
                        [weakSelf jumpMemberInfoVC:patientModel];
                    }];
                }else{
                    [weakSelf jumpMemberInfoVC:patientModel];
                }
            }
        }
        
    } failure:^(NSError *error) {
        
    }];
}
- (void)popViewController:(PatientModel *)patientModel {
    [WCBDHelper mj_insertObjectWithPatient:patientModel];

    if(self.handlePatientModelBlock){
        self.handlePatientModelBlock(patientModel);
        [self mj_popViewController];
    }
}
- (void)jumpMemberInfoVC:(PatientModel *)patientModel {
    
    [WCBDHelper mj_insertObjectWithPatient:patientModel];
    
    MJWeakSelf
    MemberInfoVC *vc = [[MemberInfoVC alloc]init];
    vc.patientModel = patientModel;
    [self.navigationController mj_pushViewController:vc animated:true completion:^{
        [weakSelf.rt_navigationController removeViewController:weakSelf];//移除控制器
    }];
    [WCBDHelper.shared mj_initPatientArray];
}

#pragma mark - 代理

#pragma mark - 懒加载

@end
